package com.ly.mpayment.rest.system;

import java.io.File;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;

import com.ly.mpayment.core.util.*;
import com.ly.mpayment.persist.entity.*;
import com.ly.mpayment.persist.service.bill.BillOrderService;
import com.ly.mpayment.persist.service.provincialinformation.IProvincialInformationService;
import com.ly.mpayment.persist.service.upshopinfo.IUpShopInfoService;
import com.ly.mpayment.persist.service.upshoppro.IUpShopProService;
import com.ly.mpayment.rest.recharge.RechargeRest;
import net.sf.json.JSONArray;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ly.mpayment.persist.service.uporder.IUporderService;
import com.ly.mpayment.persist.service.user.IUserService;
import com.ly.mpayment.rest.AbsRest;

import net.sf.json.JSONObject;

@Component
@Path("system/uporder/")
public class UpOrderRest extends AbsRest{
	Logger logger = Logger.getLogger(UpOrderRest.class);
	@Autowired
	IUserService userService;

	@Autowired
	IUporderService orderService;

	@Autowired
	IUpShopInfoService upShopInfoService;

	@Autowired
	private IUpShopProService upShopProService;

	@Autowired
	private IProvincialInformationService provincialInformationService;

	@Autowired
	BillOrderService billOrderService;


	@Path("findUpOrder")
	@POST
	public String findUpOrder(String data,@Context HttpServletRequest request){
		String result = this.validationParameterGetRole(request, userService );
		if(result == null){
			JSONObject json = JsonUtils.converToJson(data);
			Map<String, Object> parameters = MapUtil.getMap();
			return ResultMessage.getSucceed(JsonUtils.excludes(this.orderService.findPageOrder(getPage(parameters, json), json.getInt("start")
					, json.getInt("pageSize"),true), new String[]{"upOrderRefunds","upOrderLogs","downShopProduct","provincialInformation","user","","orderMatchDetails",
							"provincialInformation","operators","operatorsType","","","","errorCodesForUseruuid",
							"","phonenum","password","userstatus","usertype","token","lastlogintime","wechatid","provincecode","provincestatus",
							"provinceuuid","upOrders","downOrderLogs","downOrderRefunds","userFlow","flowInformation","downShopProduct","","downendtime"
							,"downreqid","dowonphonenum","downnotificationaddress","downendtimesec","downreqnum","busCode","callNum","callStatus",
							"","","","","","","",""}));
		}
		return result;
	}

	@Path("exportdataUpOrder")
	@POST
	public String exportdataUpOrder(String data,@Context HttpServletRequest request){
		String result = this.validationParameterGetRole(request, userService);
		if(result == null){
			JSONObject json = JsonUtils.converToJson(data);
			Map<String, Object> parameters = MapUtil.getMap();
			JSONObject obj = JsonUtils.getJSONOBJCT();
			String exportResult = ExportExcelUtil.exportUpOrder(this.orderService,getPage(parameters,json),billOrderService);
			logger.info("exportResult:"+exportResult);
			if(exportResult != null){
				obj.put("path",CookieRedis.get("download").concat(File.separator) + exportResult.replace(CookieRedis.get("exportPath"), ""));
				return ResultMessage.getSucceed(obj.toString());
			}else{
				return ResultMessage.getFailt("");
			}
		}
		return result;
	}

	private Map<String, Object> getPage(Map<String, Object> parameters,JSONObject json){
		if(!StringUtils.isBlank(json.getString("createtime"))){
			parameters.put(":createtime", json.getString("createtime"));
		}
		if(!StringUtils.isBlank(json.getString("endtime"))){
			parameters.put(":endtime", json.getString("endtime"));
		}

		if(!StringUtils.isBlank(json.getString("uporderuuid"))){
			parameters.put(":uporderuuid", json.getString("uporderuuid"));
		}

		if(!StringUtils.isBlank(json.getString("upOrderId"))){
			parameters.put(":upOrderId", json.getString("upOrderId"));
		}

		if(!StringUtils.isBlank(json.getString("upOrderIds"))){
			parameters.put(":upOrderIds", json.getString("upOrderIds"));
		}

		if(!StringUtils.isBlank(json.getString("useruuid"))){
			parameters.put(":useruuid", json.getString("useruuid"));
		}
		if(!StringUtils.isBlank(json.getString("productCode"))){
			parameters.put(":productCode", json.getString("productCode"));
		}
		if(!StringUtils.isBlank(json.getString("provinceuuid"))){
			parameters.put(":province", json.getString("provinceuuid"));
		}
		if(!StringUtils.isBlank(json.getString("busuuid"))){
			parameters.put(":busuuid", json.getString("busuuid"));
		}
		if(!StringUtils.isBlank(json.getString("phoneNum"))){
			parameters.put(":phoneNum", json.getString("phoneNum"));
		}
		if(!StringUtils.isBlank(json.getString("status"))){
			parameters.put(":status", json.getInt("status"));
		}
		if(!StringUtils.isBlank(json.getString("callback"))){
			parameters.put(":callBack", json.getInt("callback"));
		}
		if(!StringUtils.isBlank(json.getString("upfacevalue"))){
			parameters.put(":upfacevalue", json.getString("upfacevalue"));
		}
		if(!StringUtils.isBlank(json.getString("downShopName"))){
			parameters.put(":downShopName", json.getString("downShopName"));
		}
		if(!StringUtils.isBlank(json.getString("operatoruid"))){
			parameters.put(":operatoruid", json.getString("operatoruid"));
		}

		return parameters;
	}
	/**
	 * {"useruuid":"402880ec60dbc14e0160dbc5e6b20007","busuuid":"66e91602-a142-11e7-9887-fcaa1456507e","provinceuuid":"e12e9650-9f98-11e7-9dc0-fcaa1456507e",
	 * "facevalue":"4","starttime":"2018-01-11","endtime":"2018-01-09"}
	 * @param data
	 * @param request
	 * @return
	 */
	@SuppressWarnings("static-access")
	@Path("getUpCount")
	@POST
	public String getUpCount(String data,@Context HttpServletRequest request){
		if(!StringUtils.isBlank(data)){
			String result = this.validationParameterGetRole(request, userService);
			if(result == null){
				JSONObject json = JSONObject.fromObject(data);
				Map<String, Object> parameter = MapUtil.getMap();

				return ResultMessage.getSucceed( this.orderService.getUpCount(getCountSql(parameter, json),json.getInt("start"),json.getInt("pageSize")));
			}
			return result;
		}
		return ResultMessage.getSucceed(null);
	}

	private Map<String, Object> getCountSql(Map<String, Object> parameter,JSONObject json){
		if(!StringUtils.isBlank(json.getString("useruuid")) && !json.getString("useruuid").equals("0")){
			parameter.put("useruuid", json.getString("useruuid"));
		}
		if(!StringUtils.isBlank(json.getString("busuuid")) && !json.getString("busuuid").equals("0")){
			parameter.put("busuuid", json.getString("busuuid"));
		}
		if(!StringUtils.isBlank(json.getString("provinceuuid")) && !json.getString("provinceuuid").equals("0")){
			parameter.put("provinceuuid", json.getString("provinceuuid"));
		}
		if(!StringUtils.isBlank(json.getString("facevalue")) && !json.getString("facevalue").equals("0")){
			parameter.put("facevalue", json.getString("facevalue"));
		}
		if(!StringUtils.isBlank(json.getString("endtime"))){
			parameter.put("endtime", json.getString("endtime"));
		}
		if(!StringUtils.isBlank(json.getString("starttime"))){
			parameter.put("starttime", json.getString("starttime"));
		}
		return parameter;
	}
	@SuppressWarnings("static-access")
	@Path("exportDataUp")
	@POST
	public String exportDataUp(String data,@Context HttpServletRequest request){
		if(!StringUtils.isBlank(data)){
			String result = this.validationParameterGetRole(request, userService  );
			if(result == null){
				JSONObject json = JsonUtils.getJSONOBJCT().fromObject(data);
				Map<String, Object> parameter = MapUtil.getMap();
				JSONObject obj = JsonUtils.getJSONOBJCT();
				String exportResult = ExportExcelUtil.exportUp(this.orderService.exportDataUp(getCountSql(parameter, json)));
				logger.info("exportResult:"+exportResult);
				if(exportResult != null){
					obj.put("path",CookieRedis.get("download").concat(File.separator) + exportResult.replace(CookieRedis.get("exportPath"), ""));
					return ResultMessage.getSucceed(obj.toString());
				}else{
					return ResultMessage.getFailt("");
				}
			}
			return result;
		}
		return ResultMessage.getSucceed(null);
	}


	@SuppressWarnings("static-access")
	@Path("findUpFlowCount")
	@POST
	public String findUpFlowCount(String data,@Context HttpServletRequest request){
		String result = this.validationParameterGetRole( request, userService);
		if(result == null){
			JSONObject json = JSONObject.fromObject(data);
			return ResultMessage.getSucceed( orderService.findUpFlowCount(json,json.getInt("start"),json.getInt("pageSize")));
		}
		return result;
	}

	@SuppressWarnings("static-access")
	@Path("exportDataUpFlow")
	@POST
	public String exportDataUpFlow(String data,@Context HttpServletRequest request){
		String result = this.validationParameterGetRole(request, userService);
		if(result == null){
			JSONObject json = JsonUtils.getJSONOBJCT().fromObject(data);
			Map<String, Object> parameter = MapUtil.getMap();
			JSONObject obj = JsonUtils.getJSONOBJCT();
			String exportResult = ExportExcelUtil.exportUpFlow(this.orderService.exportDataUpFlow(json));
			logger.info("exportResult:"+exportResult);
			if(exportResult != null){
				obj.put("path",CookieRedis.get("download").concat(File.separator) + exportResult.replace(CookieRedis.get("exportPath"), ""));
				return ResultMessage.getSucceed(obj.toString());
			}else{
				return ResultMessage.getFailt("");
			}
		}
		return result;
	}

	@Path("batchCommitOrder")
	@POST
	public String batchCommitOrder(String data,@Context HttpServletRequest request){
		//提交渠道useruuid  数量 订单数组集合
		String result = this.validationParameterGetRole( request, userService);
		if(result == null){
			//查询所有选中的订单 并且添加入压单队列 如果订单提交渠道是当前提交渠道则不新建订单 变更订单信息 否则需要创建新的上游订单
			//要处理的订单数组
			JSONObject fromObject = JSONObject.fromObject(data);
			JSONArray arrays = JSONObject.fromObject(data).getJSONArray("uporderuuids");
			try {
				if(arrays != null && !arrays.isEmpty() && !StringUtils.isBlank(fromObject.getString("useruuid"))){
					for(int i = 0 ; i < arrays.size();i++){
						UpOrder upOrder = orderService.findByPressOrder(arrays.getJSONObject(i).getString("uporderuuid").toString());
						//渠道不变 直接提交
						if(fromObject.getString("useruuid").equals(upOrder.getUserOrder().getUseruuid())){
							UpShopInfo upShopInfo = this.upShopInfoService.findByUserId(fromObject.getString("useruuid"));
							UpOrder newOrder = this.orderService.batchCommitOrder(upOrder.getUpShopPro(),upOrder,upShopInfo);
							//检查新选的供货商是否压单
							if(!upShopInfo.getPressOrder() && !upOrder.getUpShopPro().getPressOrder()){
								logger.info("转单订单添加成功1:"+newOrder.getUpphonenum());
								RechargeRest.pressUpOrder.add(newOrder);
							}else{
								logger.info("转单订单添加成功_继续压单1:"+newOrder.getUpphonenum());
							}
						}else{
							//渠道变化 修改当前订单状态 创建新订单 还要检查新渠道产品是否匹配
							//按地市 省份 全国 查找有没有对应的产品 如果有则可以重复提交 如果没有则提示产品配置错误
							//当前渠道订单失败,需要重新创建渠道订单

							//如果产品包含地市 则优先匹配地市，否则匹配省份 全国 折扣最低的
							UpShopProduct lastProduct = upShopProService.findById(upOrder.getUpShopPro().getUpprouuid());
							if(lastProduct == null){
								return ResultMessage.getFailt("产品不存在");
							}
							String provinceuuid = "";
							//如果是全国则查询手机号所在的省份
							if(CookieRedis.get("globalCountry").equals(lastProduct.getProvincialInformation().getProvinceuuid())){
								ProvincialInformation provincialInformation = this.provincialInformationService.findByProvincename(upOrder.getProvince());
								if(provincialInformation == null){
									return ResultMessage.getFailt("省份不存在"+upOrder.getProvince());
								}
								provinceuuid = provincialInformation.getProvinceuuid();
							}else{
								provinceuuid = lastProduct.getProvincialInformation().getProvinceuuid();
							}
							//查找新渠道是否存在可以使用的产品 如果存在则加入处理队列
							List<UpShopProduct> newProducts = this.upShopProService.findNewProduct(fromObject.getString("useruuid"),
									upOrder.getOperators(),lastProduct.getProvincialInformation().getProvinceuuid(),
									lastProduct.getUpfacevalue(),upOrder.getCityName(),lastProduct.getBusinessType().getBusuuid());
							if(newProducts == null || newProducts.isEmpty()){
								newProducts = this.upShopProService.findNewProduct(fromObject.getString("useruuid"),
										upOrder.getOperators(),provinceuuid,
										lastProduct.getUpfacevalue(),"",lastProduct.getBusinessType().getBusuuid());
							}

							if(newProducts == null || newProducts.isEmpty()){
								return ResultMessage.getFailt("新供货商没有可用产品:面值"+lastProduct.getUpfacevalue());
							}
							UpShopInfo upShopInfo = this.upShopInfoService.findByUserId(fromObject.getString("useruuid"));

							UpOrder newOrder = this.orderService.batchCommitOrder(newProducts.get(0),upOrder,upShopInfo);
							//检查新选的供货商是否压单
							if(!upShopInfo.getPressOrder() && !newProducts.get(0).getPressOrder()){
								RechargeRest.pressUpOrder.add(newOrder);
								logger.info("转单订单添加成功:"+newOrder.getUpphonenum());
							}else{
								logger.info("转单订单添加成功_继续压单:"+newOrder.getUpphonenum());
							}
						}
					}
					return ResultMessage.getSucceed(null);
				}
			}catch (Exception e){
				e.printStackTrace();
				return ResultMessage.getFailt("批量处理失败，请稍后再试");
			}
		}
		return result;
	}


	@Path("repeatOrderStatus")
	@POST
	public String repeatOrderStatus(String data,@Context HttpServletRequest request){
		//提交渠道useruuid  数量 订单数组集合
		String result = this.validationParameterGetRole(request, userService);
		if(result == null){
			//查询所有选中的订单 并且添加入压单队列 如果订单提交渠道是当前提交渠道则不新建订单 变更订单信息 否则需要创建新的上游订单
			//要处理的订单数组
			JSONArray arrays = JSONObject.fromObject(data).getJSONArray("uporderuuids");
			if(arrays != null && !arrays.isEmpty()){
				for(int i = 0 ; i < arrays.size();i++){
					UpOrder upOrder = orderService.findById(arrays.getJSONObject(i).getString("uporderuuid").toString());
					if(upOrder != null && upOrder.getStatus() == Config.status[0]){
						upOrder.setStatus(Config.status[5]);
						orderService.updateOrder(upOrder);
						logger.info("repeatOrderStatus:"+upOrder.getUpphonenum()+","+upOrder.getStatus());
					}
				}
				return ResultMessage.getSucceed(null);
			}
		}
		return result;
	}




}
